<template>
  <div>
    <el-dialog class="message-form-con" top="10%" title="发送短信" width="550px" :visible.sync="messageInfoVisible" :destroy-on-close="true" :close-on-click-modal="true">
      <div class="dialog-form-con" style="margin-top:-20px;margin-left: -20px;">
        <el-form label-width="110px" :model="formdata" ref="formdata" :loading="loading" :rules="rules">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item prop="messageType">
                <template slot="label">
                  <span>短信类型:</span>
                  <el-popover
                    placement="top-start"
                    title=""
                    width="200"
                    trigger="hover"
                    content="切换时会更新短信模板可选择内容">
                    <i class="el-icon-question pointer" slot="reference"></i>
                  </el-popover>
                </template>
                <!-- <el-input size="small" v-model="formdata.messageType"></el-input> -->
                <el-select ref="messageType" clearable v-model="formdata.messageType" placeholder="请选择短信类型" width="100%" @change="handleChange('messageType')">
                  <el-option
                    v-for="(item, index) in messageTypeOptions"
                    :key="index"
                    :label="item"
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item prop="dep">
                <template slot="label">
                  <span>检查部门:</span>
                  <el-popover
                    placement="top-start"
                    title=""
                    width="200"
                    trigger="hover"
                    content="切换时会更新短信模板可选择内容">
                    <i class="el-icon-question pointer" slot="reference"></i>
                  </el-popover>
                </template>
                <!-- <el-input size="small" v-model="formdata.messageType"></el-input> -->
                <el-select clearable v-model="formdata.dep" placeholder="请选择检查部门" width="100%" @change="handleChange('dep')">
                  <el-option
                    v-for="(item, index) in depOptions"
                    :key="index"
                    :label="item"
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label-width="110px" prop="contentTemplate">
                <template slot="label">
                  <span>短信内容:</span>
                  <el-popover
                    placement="top-start"
                    title=""
                    width="200"
                    trigger="hover"
                    content="可通过右键选择需要添加的动态字段，如姓名、检查号、预约机房等">
                    <i class="el-icon-question pointer" slot="reference"></i>
                  </el-popover>
                </template>
                <div @contextmenu="showContextMenu" @click.stop="isShowContextMenu = false">
                  <!-- <textarea ref="targetInput" class="long-info" name="" id="" cols="74" rows="10" placeholder="请输入" @blur="blurEvent" v-model="ruleForm.contentTemplate"></textarea> -->
                  <!-- this.messageContents -->
                  <el-select clearable v-model="formdata.chooseContent" placeholder="请选择短信模板" style="width: 100%;" @change="handleChange('messageContent')" :popper-append-to-body="false">
                    <el-option v-for="item in messageContents" :key="item.id" :value="item.id" :label="item.contentTemplate">
                      <div class="select-flow">{{item.contentTemplate}}</div>
                    </el-option>
                  </el-select>
                  <el-input
                    ref="contentInput"
                    class="long-input"
                    maxlength="74"
                    show-word-limit
                    type="textarea"
                    size="small"
                    @input="changeChineseContent"
                    @blur="blurEvent"
                    v-model="formdata.contentTemplate"
                    placeholder="可选择上述模板或直接输入"
                    :autosize="{ minRows: 4, maxRows: 8}"></el-input>
                </div>
                <div class="context-menu" :style="{ top: contextTop + 'px', left: contextLeft + 'px' }" v-if="isShowContextMenu">
                  <el-card class="box-card" style="width: 158px;overflow: scroll;height: 300px;margin-top: 34px;">
                    <div slot="header" class="clearfix">
                      <!-- <span>插入内容</span> -->
                      <el-input suffix-icon="el-icon-search" style="position: absolute; top: 0;left: 4px; width: 158px;" v-model="filterInput" placeholder="输入关键字过滤" @input="fliterContent"></el-input>
                      <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
                    </div>
                    <div v-for="item in addfilterItem" :key="item.id" :value="item.keyName" :label="item.name">
                      <el-button style="color: black;width: 100%;height: 100%;" class="text-item" type="text" @click.stop="addKeyName(item.id)" v-if="item.name != '暂无任何结果'">{{item.name}}</el-button>
                      <p v-else>{{item.name}}</p>
                    </div>
                  </el-card>
                </div>
              </el-form-item>
              <el-form-item label-width="110px">
                <template slot="label">
                  <span>对应中文:</span>
                  <el-popover
                    placement="top-start"
                    title=""
                    width="200"
                    trigger="hover"
                    content="上方短信模板变化，会将对应字段从英文转变为中文">
                    <i class="el-icon-question pointer" slot="reference"></i>
                  </el-popover>
                </template>
                <div>
                  <el-input v-model="chineseContent" disabled class="long-input" type="textarea" size="small" placeholder="对应中文内容" :autosize="{ minRows: 2, maxRows: 10}"></el-input>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item prop="delaytime">
                <template slot="label">
                  <span>延迟时间:</span>
                  <el-popover
                    placement="top-start"
                    title=""
                    width="200"
                    trigger="hover"
                    content="时间单位为分钟">
                    <i class="el-icon-question pointer" slot="reference"></i>
                  </el-popover>
                </template>
                <el-input-number style="width: 70%;" controls-position="right" v-model="formdata.delaytime" :min="0" :max="60"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <div style="text-align: right;">
            <el-button type="primary" @click="send">发送</el-button>
            <el-button @click="closeContent">关闭</el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getItemListFunc } from '@/api/common'
import {
  getDepList,
  getMessageList,
  sendMessage,
  getItemGroupList
} from '@/api/api.js'
export default {
  data() {
    return {
      hospitalCode: this.$store.state.user.hospitalCode,
      addInfoItem: [],
      filterInput: '',
      messageInfoVisible: false,
      isShowContextMenu: false, // 控制上下文菜单的显示与隐藏
      loading: false,
      formdata: {
        messageType: '',
        delaytime: 0,
        dep: '',
        contentTemplate: '',
        accessNoList: [],
        chooseContent: ''
      },
      chineseContent: '',
      addfilterItem: [],
      messageTypeOptions: [],
      messageContents: [],
      depOptions: [],
      rules: {
        messageType: { required: true, message: '请选择短信类型', trigger: 'blur' },
        contentTemplate: { required: true, message: '请选择短信类型', trigger: 'blur' }
      }
    }
  },
  watch: {
    messageInfoVisible: {
      handler(val) {
        if (val) {
          this.setDefault()
          this.getAllListData()
          // console.error('messageContents', this.messageContents)
          // this.formdata.contentTemplate = this.messageContents[0].contentTemplate
          // this.formdata.messageType = this.messageTypeOptions[0]
        }
      },
      immediate: true
    }
  },
  mounted() {
  },
  methods: {
    async handleChange(val) {
      switch (val) {
        case 'dep':
          this.formdata.contentTemplate = ''
          this.formdata.chooseContent = ''
          this.chineseContent = ''
          this.messageContents = []
          try {
            this.getMessageList()
          } catch (err) {
            console.log(err)
          }
          break
        case 'messageType':
          this.formdata.contentTemplate = ''
          this.formdata.chooseContent = ''
          this.chineseContent = ''
          this.messageContents = []
          try {
            this.getMessageList()
          } catch (err) {
            console.log(err)
          }
          break
        case 'messageContent':
          try {
            this.formdata.contentTemplate = ''
            this.chineseContent = ''
            // this.formdata.chooseContent = ''
            // console.error('newVal', newVal)
            // console.error('this.formdata.chooseContent', this.formdata.chooseContent)
            let messageOptions = this.messageContents.filter(item => item.id === this.formdata.chooseContent)
            // console.error('messageOptions', messageOptions)
            // this.formdata.dep = messageOptions[0].dep
            // this.formdata.messageType = messageOptions[0].type
            this.formdata.contentTemplate = messageOptions[0].contentTemplate
            this.formdata.delaytime = messageOptions[0].delaytime
            // console.error('this.formdata', this.formdata)
            this.getChineseContent(this.addInfoItem)
          } catch (err) {
            console.log(err)
          }
          break
        default:
          break
      }
    },
    setDefault() {
      this.formdata.messageType = ''
      this.formdata.delaytime = 0
      this.formdata.dep = ''
      this.formdata.contentTemplate = ''
      this.formdata.messageType = ''
      // this.formdata.accessNoList = []
      this.formdata.chooseContent = ''
      this.chineseContent = ''
    },
    fliterContent() {
      if (this.filterInput != '') {
        // console.error('this.filterInput', this.filterInput)
        this.addfilterItem = this.addInfoItem.filter(item => item.name.indexOf(this.filterInput) !== -1)
        // console.error('this.addfilterItem', this.addfilterItem)
        if (this.addfilterItem.length === 0) {
          this.addfilterItem = [{ id: 0, name: '暂无任何结果', keyName: null }]
        }
      } else {
        this.addfilterItem = this.addInfoItem
      }
    },
    showContextMenu(e) {
      event.preventDefault()
      this.isShowContextMenu = true
      this.contextTop = e.clientY
      this.contextLeft = e.clientX
      // 获取被点击元素的信息（此处仅示意）
      const targetElement = e.target
      this.itemId = targetElement.dataset.id || ''
      this.itemName = targetElement.innerText || ''
      this.itemUrl = targetElement.href || ''
    },
    getChineseContent(addInfoItem) {
      // console.error('addInfoItem', addInfoItem)
      let contentCopy = this.formdata.contentTemplate
      const regex1 = /\[(.*?)\]/g
      const matches = [...contentCopy.matchAll(regex1)]
      const contents = matches.map(match => '[' + match[1] + ']')
      console.log(contents)
      addInfoItem.forEach(element => {
        if (contents.includes(element.keyName)) {
          contentCopy = contentCopy.replace(element.keyName, '[' + element.name + ']')
        }
      })
      this.chineseContent = contentCopy
    },
    changeChineseContent() {
      // console.error('addfilterItem', this.addfilterItem)
      this.getChineseContent(this.addInfoItem)
    },
    blurEvent(e) {
      this.blurStartIndex = e.srcElement.selectionStart
      e.srcElement.selectionEnd && this.blurStartIndex < e.srcElement.selectionEnd ? this.blurEndIndex = e.srcElement.selectionEnd : this.blurEndIndex = 0
      // console.log(e)
      // console.log(e.srcElement)
      // console.error('this.blurStartIndex', this.blurStartIndex) // 光标所在的位置
      // console.error('this.blurEndIndex', this.blurEndIndex)
    },
    // 短信模板
    async getMessageInfo() {
      let data = {
        HospitalCode: this.hospitalCode,
        type: '短信模板'
      }
      getItemListFunc(data).then(res => {
        let messageType = res.map(_item => {
          let newObj = {}
          newObj['keyName'] = _item.itemValue
          newObj['name'] = _item.item
          newObj['id'] = _item.id
          return newObj
        }).filter(ap => ap)
        this.addfilterItem = this.addInfoItem = messageType
        // this.getChineseContent(this.addfilterItem)
        // const messageType = res.map(_item => {_item.item}).filter(ap => ap)
        // console.error('messageType', messageType)
        // console.error('来这里了', res)
      })
    },
    // 获取检查部门数据
    getDepOptions() {
      let params = {
        hospitalCode: this.hospitalCode
      }
      return new Promise(async resolve => {
        await getDepList(params).then(res => {
          if (res.code === 10000) {
            this.depOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    // 短信类型
    async getMessageType() {
      let data = {
        HospitalCode: this.hospitalCode,
        type: '短信类型'
      }
      getItemGroupList(data).then(res => {
        if (res && res.code == 10000) {
          this.messageTypeOptions = res.content.list
        }
      })
    },
    // 获取下拉数据
    getAllListData() {
      const that = this
      return new Promise(async (resolve, reject) => {
        const res = Promise.all([
          that.getDepOptions(),
          that.getMessageType(),
          that.getMessageInfo(),
          that.getMessageList()
        ])
        if (res) {
          resolve(true)
        } else {
          reject(false)
        }
      })
    },
    addKeyName(id) {
      // 先获得要添加的内容
      const filteredItems = this.addInfoItem.filter(item => item.id === id)
      let targetInput = this.$refs.contentInput.$el.querySelector('textarea')
      let startIndex = this.blurStartIndex
      let endIndex = this.blurEndIndex
      let newEndIndex = parseInt(startIndex + filteredItems[0].keyName.length)
      // 如果开始光标小于结束光标，则由开始光标到结束光标进行内容替换，将光标最后锁定在加的内容最后
      if (startIndex < endIndex) {
        this.formdata.contentTemplate = this.formdata.contentTemplate.slice(0, startIndex) + filteredItems[0].keyName + this.formdata.contentTemplate.slice(endIndex)
        this.chineseContent = this.formdata.chineseContent.slice(0, startIndex) + '[' + filteredItems[0].name + ']' + this.formdata.chineseContent.slice(endIndex)
        // this.$nextTick(() => {
        //   targetInput.focus()
        //   targetInput.setSelectionRange(newEndIndex, newEndIndex)
        // })
        this.blurEndIndex = 0
      } else {
        // 如果开始光标大于或等于结束光标，则在开始光标后直接顺延添加
        this.formdata.contentTemplate = this.formdata.contentTemplate === null || this.formdata.contentTemplate === '' ? filteredItems[0].keyName : this.formdata.contentTemplate.slice(0, startIndex) + filteredItems[0].keyName + this.formdata.contentTemplate.slice(startIndex)
        this.chineseContent = this.chineseContent === null || this.chineseContent === '' ? '[' + filteredItems[0].name + ']' : this.chineseContent.slice(0, startIndex) + '[' + filteredItems[0].name + ']' + this.chineseContent.slice(startIndex)
        // this.$nextTick(() => {
        //   targetInput.focus()
        //   targetInput.setSelectionRange(newEndIndex, newEndIndex)
        // })
      }
      this.$nextTick(() => {
        targetInput.focus()
        targetInput.setSelectionRange(newEndIndex, newEndIndex)
      })
    },
    getMessageList() {
      let params = {
        hospitalCode: this.hospitalCode,
        type: this.formdata.messageType,
        dep: this.formdata.dep
      }
      this.messageContents = []
      return new Promise(async resolve => {
        await getMessageList(params).then(res => {
          if (res.code === 10000) {
            // console.error('数据', res)
            let message = res.content.list
            message.forEach(element => {
              this.messageContents.push({ 'contentTemplate': element.contentTemplate, 'dep': element.dep, 'type': element.type, 'id': element.id, 'delaytime': element.delaytime })
            })
            if (this.messageContents.length > 0) {
              this.formdata.contentTemplate = this.messageContents[0].contentTemplate
              this.formdata.chooseContent = this.messageContents[0].id
              this.formdata.messageType = this.messageContents[0].type
              this.formdata.delaytime = this.messageContents[0].delaytime
            }
            // console.error('this.messageContents[0]', this.messageContents[0])
            resolve(res)
          }
        })
      })
    },
    closeContent() {
      this.messageInfoVisible = false
    },
    validForm() {
      if (!this.formdata.messageType) {
        this.$message.warning('请选择短信类型')
        this.$refs.messageType.focus()
        return false
      } else if (!this.formdata.contentTemplate) {
        this.$message.warning('请输入短信模板内容')
        this.$refs.contentInput.focus()
        return false
      } else if (this.formdata.contentTemplate.length > 74) {
        this.$message.warning('您输入的文字过多请删减')
        this.$refs.contentInput.focus()
        return false
      }
      return true
    },
    send() {
      const validFlag = this.validForm()
      if (!validFlag) return
      let params = {
        hospitalCode: this.hospitalCode,
        type: this.formdata.messageType,
        delaytime: this.formdata.delaytime,
        contentTemplate: this.formdata.contentTemplate,
        accessNoList: this.formdata.accessNoList
      }
      return new Promise(async resolve => {
        await sendMessage(params).then(res => {
          if (res.code === 10000) {
            var regex = /\d+/ // 匹配连续的数字
            var result = res.message.match(regex) // 获取所有匹配到的数字
            console.log(result[0]) // 输出第一个匹配到的数字（如果存在）
            if (result[0] > 0) {
              this.$message.success(res.message)
            } else {
              this.$message.warning(res.message)
            }
            this.$emit('changeSendMessage')
            this.messageInfoVisible = false
            resolve(res)
          }
        })
      })
    }
  }
}
</script>
<style lang='scss' scoped>
  .add_department{
    font-size: 14px;
    cursor: pointer;
    color: #00c0ef;
    &:hover{
      opacity: 0.6;
    }
  }
  /deep/ .el-form-item__label{
    text-align: right;
  }
  .mianBox{
    /deep/ .el-input{
      width: 215px;
    }
    .long-input{
      width: 555px;
      /deep/ .el-input{
          width: 500px;
      }
    }
    .name{
      font-weight: bold;
    }
    .el-form--inline .el-form-item{
      margin-right:0px;
      margin-bottom: 16px;
    }
    /deep/ .el-form-item__label{
      line-height: 32px;
    }
    /deep/ .el-form-item__content{
      line-height: 32px;
    }
    .buttons{
      width: 100%;
      .el-dropdown{
        color: #00c0ef;
      }
    }
    .pointer {
      cursor: pointer;
    }
  }
  /* 自定义上下文菜单样式 */
  .context-menu {
    position: fixed; /* 或者 absolute */
    /* background-color: #fff; */
    /* border: 1px solid #ccc; */
    padding: 5px;
    z-index: 500;
  }
  .box-card >>> .el-card__body,.box-card >>> .el-card__header{
    text-align:center;
    padding: 0px;
  }
  .long-info {
    width: 100%;
    border: 0.3px solid #dcdfe6;
    border-radius: 4px;
    padding: 5px 15px;
    padding: 10px;
    font-size: 14px;
    line-height: 1.5;
    font-size: inherit;
    max-height: 300px; /* 设置最大高度 */
    transition: border-color .2s cubic-bezier(.645,.045,.355,1);
    overflow: auto; /* 超出最大高度时显示滚动条 */
  }
  .long-info:focus {
    border: 0.3px solid #dcdfe6;/* 将边框宽度设置为1px */
    /* box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2); */
    outline-color: #00C0EF;
    outline-width: 0.2px;
    outline-style: solid;
  }
  /* 输入框placeholder的样式 */
  .long-info::placeholder {
    color: #c9c9c9; /* placeholder文本颜色 */
  }
  .long-info {
    resize:vertical; /* 只能水平调整元素大小 */
  }
  /deep/ .text-item:hover{
    background-color: #dcdfe6;
  }
  .text-item{
    color: black;
    border-bottom:1px solid #ebeef5;
    transition: 0.5s;
    cursor: pointer;
  }
  .cursor{
    cursor: pointer;
  }
  .select-flow {
    width: 280px;
    display: inline-block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .message-form-con  >>> .el-dialog__body{
    padding: 30px 43px;
  }
  </style>
